package learningApp;


import java.applet.Applet;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Set;

import learningApp.Algorithm.AlgorithmSettings;
import learningApp.Algorithm.MainAlgorithm;
import learningApp.Function.IConcentratedFunction;
import learningApp.Function.XmlDefinedFunction;

public class LearningApplet extends Applet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6269945631932575705L;
	
	private String _xmlFile;
	private double _infNorm;
	private double _delta;
	private double _threshold;
	private int _dimension;
	
	private List<Set<Integer>> coeffsList;
	
	private String _lastError;
	
	public LearningApplet()
	{
		coeffsList = null;
	}
	
	public boolean setFilename(String xmlFile)
	{
		_xmlFile = xmlFile;
		return true;
	}
	
	public String getFilename()
	{
		return _xmlFile;
	}
	
	public double getInfNorm()
	{
		return _infNorm;
	}
	
	public boolean setInfNorm(double infNorm)
	{
		_infNorm = infNorm;
		return true;
	}
	
	public boolean setThreshold(double threshold)
	{
		_threshold = threshold;
		return true;
	}
	
	public boolean setDelta(double delta)
	{
		_delta = delta;
		return true;
	}
	
	public boolean setDimension(int n)
	{
		_dimension = n;
		return true;
	}
	
	public int Run()
	{		
	    InputStream inpStream = GetInputStream(_xmlFile); 
		if(inpStream == null)
		{
			return -2;
		}
		IConcentratedFunction func = new XmlDefinedFunction(inpStream, _dimension);
		if(!func.IsInitialized())
		{
			return -3;
			
		}
		final double EPSILON = 3;	//	some number...
		
		MainAlgorithm algo = new MainAlgorithm(func, new AlgorithmSettings(_delta, EPSILON, _threshold, _infNorm));
		coeffsList = algo.ListOfHeavyCoefficients();
		if(coeffsList == null)
		{
			_lastError = algo.GetLastError();
			return -1;
		}
		
		System.out.println("Found " + coeffsList.size() + " coefficients!");

		return GetNumberOfCoefficientsFound();	
	}
	
	private InputStream GetInputStream(String xmlFile)
	{
		URL source;
		InputStream inpStream;
		
		try
		{
			if(xmlFile.startsWith("file:"))
			{
				source = new URL(xmlFile);
			}
			else
			{
				source = new URL(getCodeBase(), xmlFile);
			}
			inpStream = source.openStream();
		} catch (Exception e) {
			return null;
		}
		return inpStream;
	}

	public String UnloadCoefficient()
	{
		if(coeffsList == null)
		{
			return "N/A";
		}
		String summer = "";
		for(Set<Integer> coeff : coeffsList)
		{
			for(int charac : coeff)
			{
				summer += charac + " ";
			}
			coeffsList.remove(coeff);
			break;
		}
		return summer;
	}

	public int GetNumberOfCoefficientsFound()
	{
		if(coeffsList == null)
		{
			return -1;
		}
		return coeffsList.size();
	}
	
	public String getLastError()
	{
		return _lastError;
	}
	
}
